import 'package:common_utils/common_utils.dart';
import 'package:erp/data/model/option.dart';
import 'package:erp/res/colors.dart';
import 'package:erp/res/resources.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../form_builder.dart';

class OptionSelectorFormField extends BaseFormField {
  final String name;
  final String placeholder;
  final String? label;
  final String? Function(dynamic value)? validator;
  final List<Option> options;

  OptionSelectorFormField({
    required this.name,
    required this.options,
    this.label,
    this.validator,
    this.placeholder = '请输入',
  }) : super(name: name, label: label, validator: validator);

  @override
  BaseFormFieldState createState() {
    return _OptionSelectorFormFieldState();
  }
}

class _OptionSelectorFormFieldState extends BaseFormFieldState {
  late final TextEditingController _controller;

  dynamic get initialValue {
    if (initValueMap != null && initValueMap!.containsKey(name)) {
      return initValueMap![name] ?? "";
    }
    return "";
  }

  List<Option> get options => (widget as OptionSelectorFormField).options;

  List<PickerItem<dynamic>> get adapter =>
      options.map((entry) => PickerItem(text: Text(entry.label), value: entry.value)).toList();

  @override
  Widget build(BuildContext context) {
    bool _readOnly = false;
    if (initStateMap != null && initStateMap!.containsKey('readOnly')) {
      _readOnly = initStateMap!['readOnly']!;
    }

    var valueTextColor = Colours.FORM_FIELD_VALUE_COLOR;
    var hintText = '';
    if (!_readOnly) {
      hintText = (widget as OptionSelectorFormField).placeholder;
      valueTextColor = Colours.FORM_FIELD_LABEL_COLOR;
    }
    var _widget;
    _widget = TextField(
      key: key,
      enabled: false,
      controller: _controller,
      textAlign: TextAlign.right,
      style: TextStyle(textBaseline: TextBaseline.alphabetic, fontSize: 26.sp, color: valueTextColor),
      decoration: InputDecoration(
          contentPadding: EdgeInsets.only(bottom: 2),
          border: InputBorder.none,
          enabledBorder: InputBorder.none,
          focusedBorder: InputBorder.none,
          disabledBorder: InputBorder.none,
          errorBorder: InputBorder.none,
          focusedErrorBorder: InputBorder.none,
          hintText: hintText,
          hintStyle: TextStyle(fontSize: 26.sp, color: Colours.PLACE_HOLDER_COLOR, height: 1.4)),
    );

    if (!_readOnly) {
      _widget = GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          FocusScope.of(context).requestFocus(FocusNode());
          var dataAdapter = PickerDataAdapter(data: adapter);
          List<int> selected = [];
          if (_controller.text.isNotEmpty) {
            int index = options.indexWhere((element) => element.label == _controller.text);
            selected.add(index);
          }
          await Picker(
            selecteds: selected,
            height: 220,
            itemExtent: 38,
            adapter: dataAdapter,
            onConfirm: (Picker picker, List valueList) {
              var text = options[picker.selecteds[0]].label;
              var value = options[picker.selecteds[0]].value;
              this.value = value;
              _controller.text = text;
            },
          ).showModal(context);
        },
        child: Row(
          children: [
            Expanded(
              child: _widget,
            ),
            Padding(
              padding: EdgeInsets.only(
                left: 10.w,
              ),
              child: Offstage(
                offstage: false,
                child: Container(
                  padding: EdgeInsets.only(bottom: 0),
                  child: Image.asset(
                    'assets/images/right_arrow.png',
                    width: 12.w,
                    height: 20.h,
                  ),
                ),
              ),
            )
          ],
        ),
      );
    }
    return labelWrapper(child: _widget);
  }

  @override
  void initState() {
    super.initState();
    value = '';
    _controller = TextEditingController();
  }

  void initFormManagement() {
    super.initFormManagement();
    int index = options.indexWhere((element) => element.value == initialValue);
    if (index > -1) {
      _controller.text = options[index].label;
      value = initialValue;
    }
  }

  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}

class DateSelectorFormField extends BaseFormField {
  final String name;
  final String placeholder;
  final String? label;
  final String? Function(dynamic value)? validator;

  DateSelectorFormField({
    required this.name,
    this.label,
    this.validator,
    this.placeholder = '请选择',
  }) : super(name: name, label: label, validator: validator);

  @override
  BaseFormFieldState createState() {
    return _DateSelectorFormFieldState();
  }
}

class _DateSelectorFormFieldState extends BaseFormFieldState {
  late final TextEditingController _controller;

  dynamic get initialValue {
    if (initValueMap != null && initValueMap!.containsKey(name)) {
      return initValueMap![name] ?? "";
    }
    return "";
  }

  @override
  Widget build(BuildContext context) {
    bool _readOnly = false;
    if (initStateMap != null && initStateMap!.containsKey('readOnly')) {
      _readOnly = initStateMap!['readOnly']!;
    }

    var valueTextColor = Colours.FORM_FIELD_VALUE_COLOR;
    var hintText = '';
    if (!_readOnly) {
      hintText = (widget as DateSelectorFormField).placeholder;
      valueTextColor = Colours.FORM_FIELD_LABEL_COLOR;
    }

    var _widget;
    _widget = TextField(
      key: key,
      enabled: false,
      controller: _controller,
      textAlign: TextAlign.right,
      style: TextStyle(textBaseline: TextBaseline.alphabetic, fontSize: 26.sp, color: valueTextColor),
      decoration: InputDecoration(
          contentPadding: EdgeInsets.only(bottom: 2),
          border: InputBorder.none,
          enabledBorder: InputBorder.none,
          focusedBorder: InputBorder.none,
          disabledBorder: InputBorder.none,
          errorBorder: InputBorder.none,
          focusedErrorBorder: InputBorder.none,
          hintText: hintText,
          hintStyle: TextStyle(fontSize: 26.sp, color: Colours.PLACE_HOLDER_COLOR, height: 1.4)),
    );
    if (!_readOnly) {
      _widget = GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          FocusScope.of(context).requestFocus(FocusNode());
          var adapter = DateTimePickerAdapter(
            type: PickerDateTimeType.kYMD,
            isNumberMonth: true,
            yearSuffix: "年",
            monthSuffix: "月",
            daySuffix: "日",
          );
          if (_controller.text.isNotEmpty) {
            adapter.value = DateUtil.getDateTime(_controller.text);
          }
          await Picker(
            height: 220,
            itemExtent: 38,
            adapter: adapter,
            onConfirm: (Picker picker, List valueList) {
              var value = (picker.adapter as DateTimePickerAdapter).value;
              var str = DateUtil.formatDate(value, format: 'yyyy-MM-dd');
              _controller.text = str;
              this.value = str;
            },
          ).showModal(context);
        },
        child: Row(
          children: [
            Expanded(
              child: _widget,
            ),
            Padding(
              padding: EdgeInsets.only(
                left: 10.w,
              ),
              child: Offstage(
                offstage: false,
                child: Container(
                  padding: EdgeInsets.only(bottom: 0),
                  child: Image.asset(
                    'assets/images/right_arrow.png',
                    width: 12.w,
                    height: 20.h,
                  ),
                ),
              ),
            )
          ],
        ),
      );
    }
    return labelWrapper(child: _widget);
  }

  @override
  void initState() {
    super.initState();
    value = '';
    _controller = TextEditingController();
  }

  void initFormManagement() {
    super.initFormManagement();
    _controller.text = initialValue.toString();
    value = initialValue;
  }

  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}
